package com.snjx.admui.master.common;

import java.lang.reflect.Method;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.reflect.MethodSignature;

import lombok.extern.log4j.Log4j;


/**
 * 
 * @ClassName: DataSourceAspect
 * @Description: TODO(数据源动态选择)
 * @author zyl
 * @date 2017年5月2日 下午4:46:59
 *
 */
@Log4j
public class DataSourceAspect {
	public void before(JoinPoint point) {
		
		final Object target = point.getTarget();
		final String method = point.getSignature().getName();

		final Class<?>[] classz = target.getClass().getInterfaces();

		final Class<?>[] parameterTypes = ((MethodSignature) point.getSignature()).getMethod().getParameterTypes();
		try {
			final Method m = classz[0].getMethod(method, parameterTypes);
			if (m != null && m.isAnnotationPresent(DataSource.class)) 
			{   
				//获取当前所需数据源
				final DataSource data = m.getAnnotation(DataSource.class);
				DynamicDataSourceHolder.putDataSource(data.value());
			} 
		   else 
			{
			   //默认数据源
				DynamicDataSourceHolder.putDataSource(DataSourceType.dataSource_01);
			}
		   } 
		  catch (final Exception e) {
			// 清楚数据源
			DynamicDataSourceHolder.clearDataSouce();
			log.info("catch clearDataSouce  message :"+e.getMessage());
		}
	}

}
